package com.SinaMicroblogging.TabFocused;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import com.SinaMicroblogging.LoggingPage;
import com.SinaMicroblogging.MainPage;
import com.SinaMicroblogging.PageBase;
import com.SinaMicroblogging.R;
import com.SinaMicroblogging.Extension.StatusModelAdapter;
import com.SinaMicrobloggingApi.Core.Process.SinaMicrobloggingAPIProcess;
import com.SinaMicrobloggingApi.Core.Request.PublicTimeLineRequest;
import com.SinaMicrobloggingApi.Core.Response.PublicTimeLineResponse;
import com.SinaMicrobloggingApi.Model.DirectMessagesModel;
import com.SinaMicrobloggingApi.Model.StatusModel;
import com.SinaMicrobloggingApi.Model.UserInfoModel;
import com.Util.HttpUtility;
import com.Util.String2;
import android.content.Intent;

import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HeaderViewListAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.LayoutParams;


public class HomeTabFocused extends TabFocusedBase {

	private List<StatusModel> status;
	private StatusModelAdapter statusAdapter;
	private ListView listView;
	private Handler getstatusListhandler;
	private Handler getUserAvatarhandler;
	private Handler sendStatushandler;
	private List<StatusModel> statusTemp;
	private boolean refreshable;
	final int REQUEST_COUNT = 10;
	private static Boolean firstFocus = true;
	private int preSelection = -1;
	private Button sendBtn;
	private EditText content;
	private UserInfoModel currentSelectUser;
	private static int FIRST_LOCATION = 0;
	Toast toast;
	private AlertDialog sendDialog;
	
	public HomeTabFocused() {
		status = new ArrayList<StatusModel>();
	}

	@Override
	public void OnTabFocused(PageBase page) {
		// TODO Auto-generated method stub
		if (firstFocus) {
			this.page = page;
			this.context = page.getApplicationContext();
			statusAdapter = new StatusModelAdapter(status, context);
			//statusAdapter.setReplyClick(replyClick);
			listView = (ListView) this.page.findViewById(R.id.news);
			sendBtn = (Button) this.page.findViewById(R.id.send);
			content = (EditText) this.page.findViewById(R.id.content);
			getstatusListhandler = createStatusHandler();
			getUserAvatarhandler = createUserAvatarHandler();
			sendStatushandler = createSendStatusHandler();
			LayoutParams layoutParams = new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			TextView textView = new TextView(this.page);
			textView.setPadding(0, 20, 0, 20);
			textView.setId(VIEWMORE_ID);
			textView.setText("Loading...");
			textView.setGravity(Gravity.CENTER);
			textView.setLayoutParams(layoutParams);
			textView.setTypeface(Typeface.DEFAULT_BOLD);
			textView.setTextColor(Color.BLACK);
			textView.setEms(20);
			listView.addFooterView(textView);
			listView.setAdapter(statusAdapter);
			listView.setOnItemClickListener((MainPage) this.page);
			listView.setOnScrollListener((MainPage) this.page);
			sendBtn.setOnClickListener(sendBtnClick);
			refreshable = false;
			updateStatusList();
			firstFocus = false;
		}

	}

	View.OnClickListener sendBtnClick = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String contentValue = content.getText().toString();
			if (!String2.isNullOrEmpty(contentValue)) {
				content.getText().clear();
				toast = Toast.makeText(HomeTabFocused.this.page, "posting...",
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				sendStatus(contentValue);
			} else {
				HomeTabFocused.this.page
						.showToast("send content must be fill!");
			}
		}

	};
	/*
	OnClickListener replyClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(HomeTabFocused.this,LoggingPage.class);
			//intent.setClass(HomeTabFocused.this,LoggingPage.class);
			startActivity(intent);
		}

	};
*/
	private Handler createStatusHandler() {
		Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case API_ACCESS_SUCCESS:
					if (statusTemp != null) {
						filterAndAddStatus();
						HomeTabFocused.this.statusAdapter
								.notifyDataSetChanged();
						getViewMoreTextView().setText("View More");
						getUserListAvatar();
						HomeTabFocused.this.refreshable = true;
					} else {
						HomeTabFocused.this.page
								.showToast("All of status have been shown!");
					}
					break;
				case API_ACCESS_ERROR:
					getViewMoreTextView().setText("View More");
					HomeTabFocused.this.page.showToast("Server error!");
					HomeTabFocused.this.refreshable = true;
					break;
				default:
					break;
				}
			}
		};
		return handler;
	}

	private Handler createSendStatusHandler() {
		Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case API_ACCESS_SUCCESS:
					toast.cancel();
					Bundle bundle = msg.getData();
					StatusModel status = (StatusModel) bundle.get("newStatus");
					HomeTabFocused.this.status.add(FIRST_LOCATION, status);
					HomeTabFocused.this.statusAdapter.notifyDataSetChanged();
					HomeTabFocused.this.page.showToast("post success!");
					break;
				case API_ACCESS_ERROR:
					HomeTabFocused.this.page.showToast("post failed!");
				default:
					break;
				}
			}
		};
		return handler;

	}

	private Handler createUserAvatarHandler() {
		Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case 1:
					Log.i("sinaweibo", "avatarList");
					HomeTabFocused.this.statusAdapter.notifyDataSetChanged();
					break;
				default:
					break;
				}
			}
		};
		return handler;
	}

	private void updateStatusList() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HomeTabFocused.this.statusTemp = getFriendStatusInfo();
				Message message = new Message();
				message.what = HomeTabFocused.this.statusTemp == null ? API_ACCESS_ERROR
						: API_ACCESS_SUCCESS;
				HomeTabFocused.this.getStatusListHandler().sendMessage(message);
			}

		}).start();
	}

	private void sendStatus(final String contentValue) {
		new Thread(new Runnable() {

			@Override
			public void run() {

				// TODO Auto-generated method stub
				UserInfoModel currentUser = HomeTabFocused.this.page
						.getCurrentUser();
				StatusModel status = SinaMicrobloggingAPIProcess
						.postANewStatus(currentUser.getAccessToken(),
								currentUser.getAccessTokenSecret(), currentUser
										.getUserId(),
								currentUser.getPassword(), contentValue);

				Message message = new Message();
				message.what = status == null ? API_ACCESS_ERROR
						: API_ACCESS_SUCCESS;
				Bundle bundle = new Bundle();
				bundle.putSerializable("newStatus", status);
				message.setData(bundle);
				HomeTabFocused.this.getSendStatusHandler().sendMessage(message);
			}

		}).start();
	}

	public Handler getSendStatusHandler() {
		return sendStatushandler;
	}

	public Handler getStatusListHandler() {
		return getstatusListhandler;
	}

	public Handler getUserAvatarHandler() {
		return getUserAvatarhandler;
	}

	private List<StatusModel> getFriendStatusInfo() {
		UserInfoModel currentUser = super.page.getCurrentUser();
		Log.i("sinaweibo", "getFriendStatusInfo");
		return SinaMicrobloggingAPIProcess.getFriendTimeLine(currentUser
				.getAccessToken(), currentUser.getAccessTokenSecret(),
				REQUEST_COUNT);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg2 == listView.getCount() - 1) {
			if (refreshable) {
				getViewMoreTextView().setText("Loading...");
				refreshable = false;
				updateStatusList();
			}
		} else {
			HeaderViewListAdapter headerAdatper = (HeaderViewListAdapter) arg0
					.getAdapter();
			StatusModelAdapter adapter = (StatusModelAdapter) headerAdatper
					.getWrappedAdapter();
			StatusModel statuModel = (StatusModel) adapter.getItem(arg2);
			boolean expandable = statuModel.getExpandable();
			statuModel.setExpandable(!expandable);
			if (preSelection != -1 && preSelection != arg2) {
				statuModel = (StatusModel) adapter.getItem(preSelection);
				statuModel.setExpandable(false);
			}
			adapter.notifyDataSetChanged();
			preSelection = arg2;
		}

	}

	private void filterAndAddStatus() {
		if (statusTemp != null) {
			int len = statusTemp.size();
			StatusModel statusItem;
			for (int i = 0; i < len; i++) {
				statusItem = statusTemp.get(i);
				if (!status.contains(statusItem)) {
					status.add(FIRST_LOCATION, statusItem);
				}
			}
		}
	}

	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	final int VIEWMORE_ID = 100;

	private TextView getViewMoreTextView() {
		return (TextView) HomeTabFocused.this.listView
				.findViewById(VIEWMORE_ID);
	}

	@SuppressWarnings("unchecked")
	private void getUserListAvatar() {

		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				UserInfoModel user = null;
				Bitmap userAvatar = null;
				String urlKey = null;
				SoftReference<Bitmap> bitmapRef;
				for (int i = 0; i < status.size(); i++) {
					user = status.get(i).getUser();
					urlKey = user.getProfile_image_url();
					bitmapRef = (SoftReference<Bitmap>) cache.get(urlKey);
					if (bitmapRef == null) {
						try {
							userAvatar = HttpUtility.getBitmap(urlKey);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						Log.i("sinaweibo", String.format("key is %s", urlKey));
						cache.put(urlKey, userAvatar);
					} else {
						userAvatar = bitmapRef.get();
					}
					if (userAvatar != null) {
						user.setAvatarImg(userAvatar);
						Log.i("sinaweibo", String.format("%s set avatar",
								urlKey));
						userAvatar = null;
					}
				}
				Message message = new Message();
				message.what = 1;
				HomeTabFocused.this.getUserAvatarHandler().sendMessage(message);
			}

		}).start();

	}
}
